package test.telosys.persistence.pmproxy;

import java.util.List;

import org.demo.vo.bean.Badge;
import org.telosys.persistence.TelosysPersistenceException;
import org.telosys.persistence.impl.TransactionManager;

public class ServiceA {

	ServiceB service = new ServiceB();
	
	// TODO 
	// @Transactional
	public List<Badge> saveBadgeAndReload(Badge badge, boolean errorSimulation) {

		List<Badge> allBadges = null ;
		
		// TODO : AOP - before --------------------		
		int databaseId = 0 ;
		boolean transactionStartedHere = false ;
		Exception exceptionCaught = null ;
		try {			
			
			transactionStartedHere = TransactionManager.beginTransaction(databaseId);		
			System.out.println("====== BEGIN TRANSACTION : " + transactionStartedHere + " " +  this.getClass().getSimpleName() );
		// TODO : AOP - before --------------------
			

			allBadges = service.saveBadgeAndReload(badge, errorSimulation);
			
			
		// TODO : AOP - after --------------------
			
			if ( transactionStartedHere ) {
				System.out.println("====== COMMIT " + this.getClass().getSimpleName() );
				TransactionManager.commitTransaction();
			}
			
		} catch (Exception e) {
			exceptionCaught = e ;
			if ( transactionStartedHere ) {
				System.out.println("====== ROLLBACK " + this.getClass().getSimpleName() );
				TransactionManager.rollbackTransaction();
			}
		} finally {
			if ( transactionStartedHere ) {
				System.out.println("====== CLOSE " + this.getClass().getSimpleName() );
				TransactionManager.closePersistanceManager();
			}
		}
		
		if ( exceptionCaught != null ) {
			throw new TelosysPersistenceException("Error in transaction", exceptionCaught);
		}
		// TODO : AOP - after --------------------
		
		return allBadges ;
		
	}
	
}
